<?php
namespace app\backstage\controller;
use app\backstage\logic\ManagerUserLogic;
use think\Controller;
use think\Db;
use think\facade\Request;

class Agent extends Controller
{
    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => []],
    ];

    public function index()
    {
        return $this->fetch();
    }

    public function list_data()
    {
        $params = Request::param('', '', 'strip_tags');
        $Account = \think\facade\App::model('Account', 'logic');
        $result = $Account->getAgentList($params);

        if ($result['count'] > 0) {
            return ['code' => 1, 'msg' => '数据获取成功', 'count' => $result['count'], 'data' => $result['list']];
        }

        return ['code' => 0, 'msg' => '暂无数据', 'count' => $result['count'], 'data' => $result['list']];
    }

    public function add()
    {
        if( Request::isGet() ){

            return $this->fetch();
        }

        $params = Request::post('','','strip_tags');
        $verify_result = $this->validate($params, 'Agent.add');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $ManagerUserLogic = new \app\backstage\logic\ManagerUserLogic();
        $record = $ManagerUserLogic->getInfo(['account'=>$params['account']]);
        if($record)
        {
            return json(['code'=>102,'msg'=>'账户已存在，请重新输入']);
        }

        $role_id = Db::table('cms_manager_role')->where('alias','agent')->value('id');

        $params['role_id']      = $role_id;
        $params['parent_id']    = request()->_user->id;

        $data = $ManagerUserLogic->dataProcessing($params);
        $result = $ManagerUserLogic->addInfo($data['data']);

        return json($result);
    }

    public function channel()
    {
        return $this->fetch();
    }

    public function channel_data()
    {
        $params = Request::param('', '', 'strip_tags');
        $Account = \think\facade\App::model('Account', 'logic');
        $result = $Account->getAgentList($params);

        if ($result['count'] > 0) {
            return ['code' => 1, 'msg' => '数据获取成功', 'count' => $result['count'], 'data' => $result['list']];
        }

        return ['code' => 0, 'msg' => '暂无数据', 'count' => $result['count'], 'data' => $result['list']];
    }

    public function channel_add()
    {
        if( Request::isGet() ){

            $scale_arr = [
                'C' => [
                    0 => ['field'=>'C级','value'=>'C']
                ],
                'B' => [
                    0 => ['field'=>'C级','value'=>'C'],
                    1 => ['field'=>'B级','value'=>'B']
                ],
                'A' => [
                    0 => ['field'=>'C级','value'=>'C'],
                    1 => ['field'=>'B级','value'=>'B'],
                    2 => ['field'=>'A级','value'=>'A']
                ],
                'S' => [
                    0 => ['field'=>'C级','value'=>'C'],
                    1 => ['field'=>'B级','value'=>'B'],
                    2 => ['field'=>'A级','value'=>'A'],
                    3 => ['field'=>'S级','value'=>'S']
                ],
            ];
            $scale = Db::table('cms_manager_user')->where('id',request()->_user->id)->value('scale');

            $this->assign('scales',$scale_arr[$scale]);
            return $this->fetch();
        }

        $params = Request::post('','','strip_tags');
        $verify_result = $this->validate($params, 'Agent.add');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $ManagerUserLogic = new \app\backstage\logic\ManagerUserLogic();
        $record = $ManagerUserLogic->getInfo(['account'=>$params['account']]);
        if($record)
        {
            return json(['code'=>102,'msg'=>'账户已存在，请重新输入']);
        }

        $role_id = Db::table('cms_manager_role')->where('alias','channel')->value('id');

        $params['role_id']      = $role_id;
        $params['parent_id']    = request()->_user->id;
        $params['sharing_ratio'] = Db::table('cms_manager_user')->where(['id' => request()->_user->id])->value('sharing_ratio') ?? 0;;

        $data = $ManagerUserLogic->dataProcessing($params);
        $result = $ManagerUserLogic->addInfo($data['data']);

        return json($result);
    }

    /*App授权*/
    public function empowerApp()
    {
        if( Request::isGet() ){

            $params = Request::param('','','strip_tags');
            $manager = \app\backstage\model\ManagerUser::get($params['id']);
            if (!$manager) {
                return '用户不存在';
            }
            $msg = '';
            if ($manager->role->alias == 'channel'){
                $msg = '投放号只能授权一个App';
            }
            $this->assign('msg',$msg);

            $where = [];
            if(request()->_role->alias == 'eb' || request()->_role->alias == 'agent')
            {
                $managerCur = \app\backstage\model\ManagerUser::get(request()->_user->id);
                $quick_id_gh = $this->empowerDataToJson($managerCur->apps, 1);

                $quick_id_disable = Db::table('quick_app_mp_manager_disable')->where('uid',request()->_user->id)->column('quick_id');
                foreach ($quick_id_gh as $k=>$v)
                {
                    if($quick_id_disable && in_array($v,$quick_id_disable))
                    {
                        unset($quick_id_gh[$k]);
                    }
                }
                if($quick_id_gh)
                {
                    $where[] = ['id','in',$quick_id_gh];
                }else{
                    return '该账户未存在可用App';
                }
            }

            $allQas     = \app\common\model\QuickApp::getList($where);
            $haveQas    = $manager->apps;
            $allQas     = $this->empowerDataToJson($allQas);
            $haveQas    = $this->empowerDataToJson($haveQas, 1);

            foreach ($allQas as $k => $v) {
                if (in_array($v['value'], $haveQas)) {
                    $allQas[$k]['disabled'] = true;
                }
            }

            $this->assign('allQas', json_encode($allQas));
            $this->assign('haveQas', json_encode($haveQas));
            $this->assign('params',$params);
            return $this->fetch();
        }

        $params = Request::post('','','strip_tags');
        $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.managerEmpowerApp');
        if (true !== $result) {
            $this->error($result);
        }

        $manager = \app\backstage\model\ManagerUser::get($params['id']);
        if (!$manager) {
            $this->error('用户不存在');
        }

        $where = [];
        if(request()->_role->alias == 'eb' || request()->_role->alias == 'agent')
        {
            $managerCur = \app\backstage\model\ManagerUser::get(request()->_user->id);
            $quick_id_gh = $this->empowerDataToJson($managerCur->apps, 1);
            if($quick_id_gh)
            {
                $where[] = ['id','in',$quick_id_gh];
            }else{
                $this->error('该账户未存在可用App');
            }
        }

        $allQas     = \app\common\model\QuickApp::getList($where);
        $allQas     = $this->empowerDataToJson($allQas,1);
        $quick_ids  = explode(',',$params['quick_ids']);

        foreach ($quick_ids as $k=>$v)
        {
            if(!in_array($v,$allQas))
            {
                unset($quick_ids[$k]);
            }
        }

        if(!$quick_ids)
        {
            $this->error('该账户暂无可用App');
        }

        $logic = new ManagerUserLogic();
        $result = $logic->managerEmpowerApp($manager, implode(',',$quick_ids));
        return $result;

    }

    /**
     * 格式化穿梭框所需数据
     * @param $data
     * @param int $isHave
     * @return array
     */
    private function empowerDataToJson($data, $isHave = 0)
    {
        $formatData = [];
        foreach ($data as $k => $v) {
            if ($isHave) {
                $formatData[] = $v['id'];
            } else {
                $formatData[$k]['value'] = $v['id'];
                $formatData[$k]['title'] = $v['name'];
            }
        }
        return $formatData;
    }

    /*
     * 代理充值明细
     * */
    public function recharge_list()
    {
        $ManagerUser = \think\facade\App::model('Account', 'logic');
        $agents = $ManagerUser->getAgents();

        $end_date = date('Y-m-d');
        $start_date = date('Y-m-d', strtotime('-6days'));

        $date_rang = getDateByRange($start_date, $end_date);

        $this->assign('date_rang',$date_rang);
        $this->assign('agents',$agents);
        return $this->fetch();
    }

    /*
     * 代理充值明细列表数据获取
     * */
    public function recharge_list_data()
    {
        $params = Request::param('', '', 'strip_tags');
        $Agent = \think\facade\App::model('Agent', 'logic');
        $result = $Agent->getRechargeList($params);

        if ($result['count'] > 0) {
            return ['code' => 0, 'msg' => '数据获取成功', 'count' => $result['count'], 'data' => $result['list']];
        }

        return ['code' => 1, 'msg' => '暂无数据', 'count' => $result['count'], 'data' => $result['list']];
    }

}